var express = require('express')
var User = require('./models/user')
var Topic = require('./models/topic')
var Comment = require('./models/comment')
var Follow = require('./models/follow')
var Collection = require('./models/collection')
var md5 = require('blueimp-md5')
var multer = require('multer')
var mongoose = require('mongoose')
const nodemailer = require("nodemailer")


var router = express.Router()

var storage = multer.diskStorage({
    destination: function (req, file, cb) {
      cb(null, './public/uploadImgs')
    },
    filename: function (req, file, cb) {
      cb(null, Date.now() + '-' + file.originalname)
    }
  })
  
var upload = multer({ storage: storage })


// 按话题类别分页查询话题列表
router.get('/', function (req, res, next) {
    let limit = 15  // 分页的每页条数
    let currentPage = req.query.page || 1  // 当前页码
    let tab = req.query.tab
    let newtab = ''
    if (tab == 'share') {
        newtab = '分享'
    } else if (tab == 'ask') {
        newtab = '问答'
    } else if (tab == 'job') {
        newtab = '招聘'
    } else if (tab == 'test') {
        newtab = '测试'
    } else if (tab == '' || tab == 'all') {
        newtab = ''
    }
    // find() 方法和 aggregate方法的 $match 需要的条件
    let condition = { type: newtab }
    if (newtab == '') {
        condition = {}
    }
    Topic.find(condition, function (err, all) {
        if (err) {
            next(err)
        }
        let total = all.length  // 总条数
        Topic.aggregate([
            {
                $lookup: {
                    from: "users", // 从哪个Schema中查询（一般需要复数，除非声明Schema的时候专门有处理）
                    localField: "uId", // 本地关联的字段
                    foreignField: "_id", // user中用的关联字段
                    as: "users" // 查询到所有user后放入的字段名，这个是自定义的，是个数组类型。
                }
            },
            {
                $match: condition // 按条件查询
            },
            {
                $sort: {
                    "created_time": -1  // -1：降序；1：升序
                }
            },
            {
                $skip: (parseInt(currentPage) - 1)*parseInt(limit)
            },
            {
                $limit: parseInt(limit)
            }
        ], function (err, data) {
            if (err) {
                next(err)
            }
            res.render('index.html',{
                limit: limit,
                currentPage: currentPage,
                total: total,
                data: data,
                user:req.session.user,
                tab: tab
            })
        })
    })
})


router.get('/login', function (req, res) {
    res.render('login.html')
})

router.post('/login', function (req, res, next) {
    // 1.获取表单数据
    // 2.查询数据库用户名密码是否正确
    // 3.发送响应数据
    // console.log(req.body)
    var body = req.body

    User.findOne({
        email: body.email,
        password: md5(md5(body.password))
    }, function (err, user) {
        if (err) {
            return next(err)
            // return res.status(500).json({
            //     err_code: 500,
            //     message: err.message
            // })
        }

        if (!user) {
            return res.status(200).json({
                err_code: 1,
                message: 'Email or password is invalid.'
            })
        }

        // 用户侧存在，登录成功，通过 Session 记录登录状态
        req.session.user = user

        res.status(200).json({
            err_code: 0,
            message: 'Ok'
        })
    })
})

router.get('/register', function (req, res) {
    res.render('register.html')
})

router.post('/register', function (req, res, next) {
    // 1.获取表单提交的数据
    // req.body
    // 2.操作数据库
    //   判断该用户是否存在
    //   如果已存在，不允许注册
    //   如果不存在，注册新建用户
    // 3.发送响应
    var body = req.body
    User.findOne({
        $or: [
            {
                email: body.email
            },
            {
                nickname: body.nickname
            }
        ]
    }, function (err, data) {
        if (data) {
            // 邮箱或者昵称已存在
            return res.status(200).json({
                err_code: 1,
                message: 'Email or nickname already exists'
            })
        }

        // 对密码进行 md5 重复加密
        body.password = md5(md5(body.password))
        new User(body).save(function (err, user) {
            if (err) {
                // return res.status(500).json({
                //     err_code: 500,
                //     message: 'Internal error'
                // })
                return next(err)
            }

            // 注册成功，使用 Session 记录用户的登陆状态
            req.session.user = user

            // Express 提供了一个响应方法：json
            // 该方法接收一个对象作为参数，它会自动帮你把对象转为字符串再发送给浏览器
            res.status(200).json({
                err_code: 0,
                message: 'Ok'
            })

            // 服务端重定向只针对同步请求才有效，异步请求无效
            // res.redirect('/')
        })
    })
})

router.get('/logout', function (req, res) {
    // 清除登录状态
    req.session.user = null
    // 重定向到登录页
    res.redirect('/login')
})

router.get('/settings/profile', function (req, res) {
    res.render('settings/profile.html', {
        user: req.session.user
    })
})

// 修改个人主页信息
router.post('/settings/profile', function (req, res, next) {
    var id = req.body.id.replace(/"/g, '')
    User.findOneAndUpdate({
        _id:id
    }, {
        $set:req.body
    }).then(function(user){
        user.nickname = req.body.nickname
        user.gender = req.body.gender
        user.birthday = req.body.birthday
        user.bio = req.body.bio
        req.session.user = user
        res.redirect('/settings/profile')
    },function(err){
        if (err) {
            next(err)
        }
    })
})

// 更换头像
router.post('/upload', upload.single('avatar'), function (req, res, next) {
    var id = req.body.id.replace(/"/g, '')
    User.findOneAndUpdate({
        _id:id
    }, {
        $set:{
            avatar: '/public/uploadImgs/' + req.file.filename
        }
    }).then(function(user){
        user.avatar = '/public/uploadImgs/' + req.file.filename
        req.session.user = user
        res.redirect('/settings/profile')
    },function(err){
        if (err) {
            next(err)
        }
    })
})

router.get('/settings/admin', function (req, res) {
    res.render('settings/admin.html', {
        user: req.session.user
    })
})

// 查找密码是否匹配
router.post('/findPwd', function (req, res, next) {
    // console.log(req.body)
    User.findOne({
        _id: req.body.id
    }, function (err, data) {
        if (err) {
            next(err)
        }
        if (md5(md5(req.body.password)) === data.password) {
            res.status(200).json({
                err_code: 0,
                data: data
            })
        } else if (md5(md5(req.body.password)) != data.password) {
            res.status(200).json({
                err_code: 1,
                data: data
            })
        }
    })
})

// 修改密码
router.post('/updatePwd', function (req, res, next) {
    // console.log(req.body)
    var id = req.body.id.replace(/"/g, '')
    User.findOneAndUpdate({
        _id:id
    }, {
        $set:{
            password: md5(md5(req.body.password))
        }
    }).then(function(user){
        user.password = md5(md5(req.body.password))
        req.session.user = user
        res.status(200).json({
            err_code: 0,
            message: '恭喜您，密码修改成功!'
        })
    },function(err){
        if (err) {
            next(err)
        }
    })
})

// 个人设置页查看登录用户创建的所有话题
router.get('/settings/createdTopics', function (req, res, next) {
    let limit = 15
    let currentPage = req.query.page || 1
    // 聚合查询条件
    let pipeLine = {
        $lookup: {
            from: "users",
            localField: "uId",
            foreignField: "_id",
            as: "users"
        }
    }

    User.findOne({
        nickname: req.session.user.nickname
    }, function (err, currentuser) {
        if (err) {
            next(err)
        } else {
            new Promise(function (resolve, reject) {
                Topic.aggregate([
                    pipeLine,
                    {
                        $match: {
                            uId: mongoose.Types.ObjectId(currentuser._id)
                        }
                    }
                ], function (err, topic) {
                    if (err) {
                        reject(err)
                    } else {
                        resolve(topic)
                    }
                })
            })
            .then(function (topic) {
                let total = topic.length
                Topic.aggregate([
                    pipeLine,
                    {
                        $match: {
                            uId: mongoose.Types.ObjectId(currentuser._id)
                        }
                    },
                    {
                        $skip: parseInt(currentPage - 1) * parseInt(limit)
                    },
                    {
                        $limit: parseInt(limit)
                    }
                ], function (err, topiclimit) {
                    if (err) {
                        next(err)
                    } else {
                        res.render('settings/createdTopics.html', {
                            currentuser: currentuser,
                            topic: topiclimit,
                            user: req.session.user,
                            total: total,
                            currentPage: currentPage,
                            limit: limit
                        })
                    }
                })
            })
        }
    })
})

// 个人设置页查看登录用户参与的所有话题
router.get('/settings/partTopics', function (req, res, next) {
    let limit = 15
    let currentPage = req.query.page || 1
    // 聚合查询条件
    let pipeLine1 = {
        $lookup: {
            from: "users",
            localField: "uId",
            foreignField: "_id",
            as: "users"
        }
    }
    let pipeLine2 = {
        $lookup: {
            from: "topics",
            localField: "tId",
            foreignField: "_id",
            as: "topics"
        }
    }
    User.findOne({
        nickname: req.session.user.nickname
    }, function (err, currentuser) {
        if (err) {
            next(err)
        } else {
            new Promise(function (resolve, reject) {
                Comment.aggregate([
                    pipeLine1,
                    pipeLine2,
                    {
                        $match: {
                            uId: mongoose.Types.ObjectId(currentuser._id)
                        }
                    }
                ], function (err, commentAll) {
                    if (err) {
                        reject(err)
                    } else {
                        resolve(commentAll)
                    }
                })
            })
            .then(function (commentAll) {
                let total = commentAll.length
                Comment.aggregate([
                    pipeLine1,
                    pipeLine2,
                    {
                        $match: {
                            uId: mongoose.Types.ObjectId(currentuser._id)
                        }
                    },
                    {
                        $skip: parseInt(currentPage - 1) * parseInt(limit)
                    },
                    {
                        $limit: parseInt(limit)
                    }
                ], function (err, comment) {
                    if (err) {
                        next(err)
                    } else {
                        var ids = []
                        comment.forEach(function (item) {
                            ids.push(item.topics[0].uId)
                        })
                        User.find({ _id: { $in: ids } }).then(function (author) {
                            res.render('settings/partTopics.html', {
                                currentuser: currentuser,
                                comment: comment,
                                authors: author, 
                                user: req.session.user,
                                total: total,
                                currentPage: currentPage,
                                limit: limit
                            })
                        })
                    }
                })
            })
        }
    })
})

// 根据用户昵称查看个人主页
router.get('/settings/:nickname', function (req, res) {
    User.findOne({
        nickname: req.params.nickname
    }).then(function (currentuser) {
        Topic.aggregate([
            {
                $lookup: {
                    from: "users",
                    localField: "uId",
                    foreignField: "_id",
                    as: "users"
                }
            },
            {
                $match: {
                    uId: mongoose.Types.ObjectId(currentuser._id)
                }
            },
            {
                $limit: 15
            }
        ]).then(function (topic) {
            Comment.aggregate([
                {
                    $lookup: {
                        from: "users",
                        localField: "uId",
                        foreignField: "_id",
                        as: "users"
                    }
                },
                {
                    $lookup: {
                        from: "topics",
                        localField: "tId",
                        foreignField: "_id",
                        as: "topics"
                    }
                },
                {
                    $match: {
                        uId: mongoose.Types.ObjectId(currentuser._id)
                    }
                },
                {
                    $limit: 15
                }
            ]).then(function (comment) {
                var ids = [];
                comment.forEach(function (item) {
                    ids.push(item.topics[0].uId);
                })
                User.find({ _id:{ $in:ids } }).then(function(data){
                    res.render('settings/userInfo.html',{
                        currentuser: currentuser,
                        topic: topic,
                        comment: comment,
                        authors:data,
                        user: req.session.user
                    })
                })
            })
        })
    })
})

// 分页查看用户创建的所有话题
router.get('/settings/:nickname/topics', function (req, res, next) {
    let limit = 15
    let currentPage = req.query.page || 1
    // 聚合查询条件
    let pipeLine = {
        $lookup: {
            from: "users",
            localField: "uId",
            foreignField: "_id",
            as: "users"
        }
    }

    User.findOne({
        nickname: req.params.nickname
    }, function (err, currentuser) {
        if (err) {
            next(err)
        } else {
            new Promise(function (resolve, reject) {
                Topic.aggregate([
                    pipeLine,
                    {
                        $match: {
                            uId: mongoose.Types.ObjectId(currentuser._id)
                        }
                    }
                ], function (err, topic) {
                    if (err) {
                        reject(err)
                    } else {
                        resolve(topic)
                    }
                })
            })
            .then(function (topic) {
                let total = topic.length
                Topic.aggregate([
                    pipeLine,
                    {
                        $match: {
                            uId: mongoose.Types.ObjectId(currentuser._id)
                        }
                    },
                    {
                        $skip: parseInt(currentPage - 1) * parseInt(limit)
                    },
                    {
                        $limit: parseInt(limit)
                    }
                ], function (err, topiclimit) {
                    if (err) {
                        next(err)
                    } else {
                        res.render('topic/topicList.html', {
                            currentuser: currentuser,
                            topic: topiclimit,
                            user: req.session.user,
                            total: total,
                            currentPage: currentPage,
                            limit: limit
                        })
                    }
                })
            })
        }
    })
})

// 分页查看用户参与的所有话题
router.get('/settings/:nickname/replies', function (req, res, next) {
    let limit = 15
    let currentPage = req.query.page || 1
    // 聚合查询条件
    let pipeLine1 = {
        $lookup: {
            from: "users",
            localField: "uId",
            foreignField: "_id",
            as: "users"
        }
    }
    let pipeLine2 = {
        $lookup: {
            from: "topics",
            localField: "tId",
            foreignField: "_id",
            as: "topics"
        }
    }
    User.findOne({
        nickname: req.params.nickname
    }, function (err, currentuser) {
        if (err) {
            next(err)
        } else {
            new Promise(function (resolve, reject) {
                Comment.aggregate([
                    pipeLine1,
                    pipeLine2,
                    {
                        $match: {
                            uId: mongoose.Types.ObjectId(currentuser._id)
                        }
                    }
                ], function (err, commentAll) {
                    if (err) {
                        reject(err)
                    } else {
                        resolve(commentAll)
                    }
                })
            })
            .then(function (commentAll) {
                let total = commentAll.length
                Comment.aggregate([
                    pipeLine1,
                    pipeLine2,
                    {
                        $match: {
                            uId: mongoose.Types.ObjectId(currentuser._id)
                        }
                    },
                    {
                        $skip: parseInt(currentPage - 1) * parseInt(limit)
                    },
                    {
                        $limit: parseInt(limit)
                    }
                ], function (err, comment) {
                    if (err) {
                        next(err)
                    } else {
                        var ids = []
                        comment.forEach(function (item) {
                            ids.push(item.topics[0].uId)
                        })
                        User.find({ _id: { $in: ids } }).then(function (author) {
                            res.render('topic/repliesList.html', {
                                currentuser: currentuser,
                                comment: comment,
                                authors: author, 
                                user: req.session.user,
                                total: total,
                                currentPage: currentPage,
                                limit: limit
                            })
                        })
                    }
                })
            })
        }
    })
})

// 查看用户关注的所有其他用户
router.get('/myFollow', function (req, res) {
    Follow.aggregate([
        {
            $lookup: {
                from: "users",
                localField: "uId",
                foreignField: "_id",
                as: "followuser"
            }
        },
        {
            $match: {
                aId: mongoose.Types.ObjectId(req.session.user._id)
            }
        }
    ]).then(function (follow) {
        res.render('settings/follow.html',{
            follow: follow,
            user:req.session.user
        })
    })
})

// 查看当前登录用户的粉丝
router.get('/myFans', function (req, res) {
    Follow.aggregate([
        {
            $lookup: {
                from: "users",
                localField: "aId",
                foreignField: "_id",
                as: "fansuser"
            }
        },
        {
            $match: {
                uId: mongoose.Types.ObjectId(req.session.user._id)
            }
        }
    ]).then(function (fans) {
        res.render('settings/fans.html',{
            fans: fans,
            user:req.session.user
        })
    })
})

// 分页查看用户收藏的话题
router.get('/myCollection', function (req, res) {
    let limit = 15  // 分页的每页条数
    let currentPage = req.query.page || 1  // 当前页码
    Collection.find({ uId: req.session.user._id }).then(function (allCollection) {
        let total = allCollection.length
        Collection.aggregate([
            {
                $lookup: {
                    from: "users",
                    localField: "uId",
                    foreignField: "_id",
                    as: "collecteuser"
                }
            },{
                $lookup: {
                    from: "topics",
                    localField: "tId",
                    foreignField: "_id",
                    as: "collectetopic"
                }
            },
            {
                $match: {
                    uId: mongoose.Types.ObjectId(req.session.user._id)
                }
            },
            {
                $skip: (parseInt(currentPage) - 1)*parseInt(limit)
            },
            {
                $limit: parseInt(limit)
            }
        ]).then(function (limitCollection) {
            let ids = []
            limitCollection.forEach(function (item) {
                ids.push(item.collectetopic[0].uId)
            })
            User.find({ _id: { $in: ids } }).then(function (authors) {
                res.render('settings/collection.html',{
                    limit: limit,
                    currentPage: currentPage,
                    total: total,
                    data: limitCollection,
                    user:req.session.user,
                    authors: authors
                })
            })
        })
    })
})

// 话题相关部分
router.get('/topic/new', function (req, res) {
    res.render('topic/new.html', {
        user: req.session.user
    })
})

// 添加话题
router.post('/topic/new', function (req, res, next) {
    // console.log(req.body)
    // 先保存话题，然后在查询并修改用户积分
    var id = req.body.uId.replace(/"/g, '')
    new Topic(req.body).save(function (err, data) {
        if (err) {
            next(err)
        }

        User.findOneAndUpdate({
            _id: id
        }, {
            $set:{
                score: req.session.user.score + 10
            }
        }).then(function(user){
            user.score = req.session.user.score + 10
            req.session.user = user

            res.status(200).json({
                err_code: 0,
                message: 'Ok'
            })
        },function(err){
            if (err) {
                next(err)
            }
        })
    })
})

// 查看话题详情和评论详情(根据话题id)，还有用户收藏，关注，评论点赞的情况
router.get('/topic/show/:_id', function (req, res) {
    Topic.aggregate([
        {
            $lookup: {
                from: "users",
                localField: "uId",
                foreignField: "_id",
                as: "users"
            }
        },
        {
            $match: {
                _id: mongoose.Types.ObjectId(req.params._id)
            }
        }
    ]).then(function (topic) {
        Topic.findOneAndUpdate({
            _id: mongoose.Types.ObjectId(req.params._id)
        }, {
            $set:{
                click_num: topic[0].click_num + 1
            }
        }).then(function(currentTopic){
            currentTopic.click_num = topic[0].click_num + 1
            topic[0].click_num = currentTopic.click_num
            Comment.aggregate([
                {
                    $lookup: {
                        from: "users",
                        localField: "uId",
                        foreignField: "_id",
                        as: "users"
                    }
                },
                {
                    $match: {
                        tId: mongoose.Types.ObjectId(req.params._id)
                    }
                }
            ]).then(function (comment) {
                // 判断用户是否登录
                if (req.session.user) {
                    Follow.aggregate([
                        {
                            $lookup: {
                                from: "users",
                                localField: "uId",
                                foreignField: "_id",
                                as: "followuser"
                            }
                        },
                        {
                            $match: {
                                aId: mongoose.Types.ObjectId(req.session.user._id)
                            }
                        }
                    ]).then(function (follow) {
                        Collection.aggregate([
                            {
                                $lookup: {
                                    from: "users",
                                    localField: "uId",
                                    foreignField: "_id",
                                    as: "collecteuser"
                                }
                            },{
                                $lookup: {
                                    from: "topics",
                                    localField: "tId",
                                    foreignField: "_id",
                                    as: "collectetopic"
                                }
                            },
                            {
                                $match: {
                                    uId: mongoose.Types.ObjectId(req.session.user._id)
                                }
                            }
                        ]).then (function (collection) {
                            // 判断是否关注
                            let isFollow = false
                            let followId = ''
                            follow.forEach(function (item) {
                                if (JSON.stringify(item.uId) == JSON.stringify(topic[0].users[0]._id)) {
                                    isFollow = true
                                    followId = item._id
                                }
                            })
                            // 判断是否收藏
                            let isCollecte = false
                            let collecteId = ''
                            collection.forEach(function (it) {
                                if (JSON.stringify(it.tId) == JSON.stringify(topic[0]._id)) {
                                    isCollecte = true
                                    collecteId = it._id
                                }
                            })
                            let thumbNum = []  // 点赞数数组
                            // 判断是否点赞
                            comment.forEach(function (item) {
                                thumbNum.push(item.thumbs.length)
                                item.thumbs.forEach(function (inner) {
                                    if(JSON.stringify(req.session.user._id) == JSON.stringify(inner)) {
                                        item.isThumbs = true
                                    }
                                })
                            })
                            res.render('topic/show.html',{
                                topic: topic,
                                comment: comment,
                                user:req.session.user,
                                isFollow: isFollow,
                                followId: followId,
                                isCollecte: isCollecte,
                                collecteId: collecteId,
                                thumbNum: thumbNum
                            })
                        })
                    })
                } else {
                    res.render('topic/show.html',{
                        topic: topic,
                        comment: comment,
                        user:req.session.user
                    })
                }
            })
        })
    })
})

// 处理编辑话题
router.get('/topic/edit/:_id', function (req, res, next) {
    Topic.findById(req.params._id, function (err, topic){
		if (err) {
			next(err)
		}
		res.render('topic/edit.html', {
            topic: topic,
            user: req.session.user
        })
    })
})

// 处理编辑话题表单提交
router.post('/topic/edit', function (req, res, next) {
    req.body.last_modified_time = new Date()
	Topic.findByIdAndUpdate(req.body.id, req.body, function (err) {
		if (err) {
			next(err)
		}
		res.redirect('/topic/show/' + mongoose.Types.ObjectId(req.body.id))
	})
})

// 处理删除话题
router.get('/topic/delete/:_id', function (req, res, next) {
    Topic.findByIdAndRemove(req.params._id, function (err) {
		if (err) {
			next(err)
		}
		res.redirect('/settings/createdTopics')
	})
})

// 评论相关部分

// 添加评论
router.post('/comment/new', function (req, res, next) {
    var id = req.body.uId
    new Comment(req.body).save(function (err, data) {
        if (err) {
            next(err)
        }
        Comment.aggregate([
            {
                $lookup: {
                    from: "topics",
                    localField: "tId",
                    foreignField: "_id",
                    as: "topic"
                }
            },
            {
                $match: {
                    tId: mongoose.Types.ObjectId(data.tId)
                }
            }
        ]).then(function (comment) {
            Topic.findOneAndUpdate({
                _id: mongoose.Types.ObjectId(data.tId)
            }, {
                $set:{
                    call_num: comment[0].topic[0].call_num + 1
                }
            }).then(function(currentTopic){
                currentTopic.call_num = comment[0].topic[0].call_num + 1
                User.findOneAndUpdate({
                    _id: id
                }, {
                    $set:{
                        score: req.session.user.score + 5
                    }
                }).then(function(user){
                    user.score = req.session.user.score + 5
                    req.session.user = user
        
                    res.status(200).json({
                        err_code: 0,
                        message: 'Ok'
                    })
                },function(err){
                    if (err) {
                        next(err)
                    }
                })
            })
        })
    })
})

// 删除评论
router.get('/comment/delete/:_id', function (req, res, next) {
    Comment.aggregate([
        {
            $lookup: {
                from: "topics",
                localField: "tId",
                foreignField: "_id",
                as: "topic"
            }
        },
        {
            $match: {
                _id: mongoose.Types.ObjectId(req.params._id)
            }
        }
    ]).then(function (comment) {
        Topic.findOneAndUpdate({
            _id: mongoose.Types.ObjectId(comment[0].tId)
        }, {
            $set:{
                call_num: comment[0].topic[0].call_num - 1
            }
        }).then(function(currentTopic){
            Comment.findByIdAndRemove(req.params._id, function (err) {
                if (err) {
                    next(err)
                }
                res.redirect('/settings/partTopics')
            })
        })
    })
})

// 根据评论 _id 为当前评论添加点赞
router.post('/comment/thumb/:_id', function (req, res, next) {
    // console.log(req.body.thumbOne)
    Comment.findOneAndUpdate({
        _id: mongoose.Types.ObjectId(req.params._id)
    }, {
        $addToSet:{
            thumbs: req.body.thumbOne
        }
    }).then(function(currentComment){
        res.status(200).json({
            err_code: 0,
            message: 'Ok'
        })
    })
})

// 根据评论 _id 为当前评论取消点赞
router.get('/comment/deleteThumb/:_id', function (req, res) {
    Comment.findOneAndUpdate({
        _id: mongoose.Types.ObjectId(req.params._id)
    }, {
        $pull:{
            thumbs: req.session.user._id
        }
    }).then(function(currentComment){
        res.status(200).json({
            err_code: 0,
            message: 'Ok'
        })
    })
})

// 关注相关部分

// 添加关注
router.post('/follow/new', function (req, res, next) {
    // console.log(req.body)
    new Follow(req.body).save(function (err, data) {
        if (err) {
            next(err)
        }
        res.status(200).json({
            err_code: 0,
            message: 'Ok'
        })
    })
})

// 取消关注
router.get('/follow/delete/:_id', function (req, res, next) {
    Follow.findByIdAndRemove(req.params._id, function (err) {
        if (err) {
            next(err)
        }
        res.status(200).json({
            err_code: 0,
            message: 'Ok'
        })
    })
})

// 个人设置页取消关注
router.get('/follow/deleteById/:_id', function (req, res, next) {
    Follow.findByIdAndRemove(req.params._id, function (err) {
        if (err) {
            next(err)
        }
        res.redirect('/myFollow')
    })
})


// 收藏相关部分

// 添加收藏
router.post('/collection/new', function (req, res, next) {
    new Collection(req.body).save(function (err, data) {
        if (err) {
            next(err)
        }
        res.status(200).json({
            err_code: 0,
            message: 'Ok'
        })
    })
})

// 取消收藏
router.get('/collection/delete/:_id', function (req, res, next) {
    Collection.findByIdAndRemove(req.params._id, function (err) {
        if (err) {
            next(err)
        }
        res.status(200).json({
            err_code: 0,
            message: 'Ok'
        })
    })
})

// 个人设置也取消收藏
router.get('/collection/deleteById/:_id', function (req, res, next) {
    Collection.findByIdAndRemove(req.params._id, function (err) {
        if (err) {
            next(err)
        }
        res.redirect('/myCollection')
    })
})


// 忘记密码
router.get('/forgetPwd', function (req, res) {
    res.render('forgetPwd.html')
})


// 发送邮件获取验证码
router.get('/getCodeAndSendMail/:email', function (req, res) {
    User.findOne({ email: req.params.email })
    .then(function (user) {
        if (user) {
            let random = Math.random()
            let code = random.toString().substring(2,8)
            console.log(random)
            console.log(code)
            let transporter = nodemailer.createTransport({
                service: 'qq',
                secureConnection: true,
                secure: true,
                port: 465,
                auth:{
                    user:"1737770335@qq.com",
                    pass:"vznzgpnpfmnsfbjh"
                }
            })
            let mailOptions = {
                from: '"Yrainly" <1737770335@qq.com>',
                to: req.params.email,
                subject: "node.js 社区更改账号信息验证码：" + code,
                text: "node.js 社区更改账号信息验证码：" + code,
                html: "您好！您此次更改当前账号信息的验证码为：<b>" + code + "</b>，5分钟内有效，验证码提供给他人可能导致账号被盗，请勿泄露，谨防被骗。" 
            }
            transporter.sendMail(mailOptions,(err,data) => {
                if(err){
                    console.log(err);
                    res.status(200).json({
                        err_code: -1,
                        message: 'Failed to send mail.'
                    })
                }else{
                    res.status(200).json({
                        err_code: 0,
                        message: 'Ok.',
                        code: code
                    })
                }
            })
        } else {
            res.status(200).json({
                err_code: 1,
                message: 'Sorry! this email does not exist.'
            })
        }
    })
})

// 忘记密码后修改密码
router.post('/updateNewPwd', function (req, res, next) {
    User.findOneAndUpdate({
        email:req.body.email
    }, {
        $set:{
            password: md5(md5(req.body.password))
        }
    }).then(function(user){
        user.password = md5(md5(req.body.password))
        req.session.user = user
        res.status(200).json({
            err_code: 0,
            message: '恭喜您，密码修改成功!'
        })
    },function(err){
        if (err) {
            next(err)
        }
    })
})


module.exports = router
